package com.bbcare.department.plat.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.OSSClientUtil;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.QueryModel;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.entity.Doctor;
import com.bbcare.department.plat.entity.ScheduleDuty;
import com.bbcare.department.plat.service.IBsStaticParamService;
import com.bbcare.department.plat.service.IDoctorManagerService;

@Controller
@RequestMapping("/service/doctor")
public class DoctorManagerController {

	Logger logger = Logger.getLogger(DoctorManagerController.class);

	@Autowired
	private IDoctorManagerService doctorManagerService;

	@Autowired
	private IBsStaticParamService bsStaticParamService;
	/**
	 * 科室医生职称列表
	 * @param request
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/doctorTitle/list")
	public ResultModel<List<Map<String, Object>>> getDoctorTitleList(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in getDoctorTitleList----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
		//
		Map<String,Object> paramTemp = new HashMap<String,Object>();

		 // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户
        String deptId = (String) sessionMap.get("rootGroupId");
		paramTemp.put("deptId",deptId);
		paramTemp.put("tenantId",tenantId);
		paramTemp.put("type",Constants.DOCTOR_TITLE_TYPE_CODE);

		List<Map<String,Object>> list = bsStaticParamService.getStaticParamsByCondition(paramTemp);
		logger.info("out getDoctorTitleList----arg==" + list);
		return new ResultModel<List<Map<String,Object>>>(list);
	}

	/**
	 * 科室医生职称列表
	 * @param request
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/scheduleType/list")
	public ResultModel<List<Map<String, Object>>> getScheduleTypeList(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in getScheduleTypeList----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
		//
		Map<String,Object> paramTemp = new HashMap<String,Object>();

		 // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String deptId = (String) sessionMap.get("tenantId");// 租户id

		paramTemp.put("deptId",deptId);
		paramTemp.put("type",Constants.SCHEDULE_TYPE_CODE);
		List<Map<String,Object>> list = bsStaticParamService.getStaticParamsByCondition(paramTemp);
		logger.info("out getDoctorTitleList----arg==" + list);
		return new ResultModel<List<Map<String,Object>>>(list);
	}

	/**
	 * 医生基本详情信息
	 * @param request
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/basicinfo/detail")
	public ResultModel<Doctor> getDoctorBasicDetail(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in getDoctorBasicDetail----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String id = requestParam.getString("doctorId");
        if(StringUtils.isEmpty(id)){
        	logger.debug("out getDoctorBasicDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，医生ID不能为空");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String deptId = (String) sessionMap.get("rootGroupId");// 科室id
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        Map<String,Object> paramTemp = new HashMap<String,Object>();
        paramTemp.put("id", id);
        Doctor doctor = doctorManagerService.getDoctorById(paramTemp);

        if(null == doctor){
        	throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DOCTOR_NOT_EXIST, "查询的医生信息不存在");
        }
        paramTemp = new HashMap<String,Object>();
		paramTemp.put("deptId",deptId);
		paramTemp.put("type",Constants.DOCTOR_TITLE_TYPE_CODE);
		paramTemp.put("paramCode", doctor.getDoctorTitle());
		List<Map<String,Object>> list = bsStaticParamService.getStaticParamsByCondition(paramTemp);
		if(!CollectionUtils.isEmpty(list)){
			//
			String titleName = (String)list.get(0).get("paramName");
			doctor.setDoctorTitleName(titleName);
		}

		logger.info("out getDoctorBasicDetail----arg==" + doctor);
		return new ResultModel<Doctor>(doctor);
	}

	/**
	 * 根据科室Id 集合查询条件  查询医生列表
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/basicinfo/query")
	public QueryModel<Doctor> getDoctorlistByCondition(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in getDoctorlist----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);

        String requestStr = jsonEsb.getString(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        JSONObject requestParam = null;
        if(!StringUtils.isEmpty(requestStr)){
        	requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        }
        Map<String,Object> paramMap = new HashMap<String,Object>();
        if(null != requestParam){
        	paramMap.putAll(requestParam);
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("deptId");// 科室id
        paramMap.put("deptId",deptId);
        paramMap.put("tenantId",tenantId);

        int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
		paramMap.put("page", rows*(page-1));
		paramMap.put("rows", rows);

        List<Doctor> doctors = doctorManagerService.getDoctorsByCondition(paramMap);

        Map<String,Object> titleParam = new HashMap<String,Object>();
        titleParam.put("deptId",deptId);
        titleParam.put("type",Constants.DOCTOR_TITLE_TYPE_CODE);
        Map<String,String> titleMap = bsStaticParamService.getStaticParamsForMap(titleParam);

        //拼医生职称中文名字
        Doctor doctor =null;
        if(!CollectionUtils.isEmpty(doctors)){
        	for(int i = 0;i<doctors.size();i++){
        		doctor = doctors.get(i);
        		doctors.get(i).setDoctorTitleName(titleMap.get(doctor.getDoctorTitle()));
            }
        }

        Integer count = doctorManagerService.getDoctorCountByDeptId(paramMap);
		logger.info("out getDoctorlist----arg==" + doctors);
		return new QueryModel<Doctor>(doctors,count);
	}

	/**
	 * 根据科室Id 集合查询条件  查询医生列表  datatable
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/basicinfo/queryForDataTable")
	public Map<String, Object> getDoctorlistForDataTable(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in getDoctorlist----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);

        String requestStr = jsonEsb.getString(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        JSONObject requestParam = null;
        if(!StringUtils.isEmpty(requestStr)){
        	requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        }
        Map<String,Object> paramMap = new HashMap<String,Object>();
        if(null != requestParam){
        	paramMap.putAll(requestParam);
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("deptId");// 科室id
        paramMap.put("deptId",deptId);
        paramMap.put("tenantId",tenantId);

        // 针对Datatable特殊处理
        String jsonargs = requestParam.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonargs)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonargs);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("page", jsonTable.getIntValue("start"));
            paramMap.put("rows", jsonTable.getIntValue("length"));
        }

        List<Doctor> doctors = doctorManagerService.getDoctorsByCondition(paramMap);

        Map<String,Object> titleParam = new HashMap<String,Object>();
        titleParam.put("deptId",deptId);
        titleParam.put("type",Constants.DOCTOR_TITLE_TYPE_CODE);
        Map<String,String> titleMap = bsStaticParamService.getStaticParamsForMap(titleParam);

        Map<String,Object> typeParam = new HashMap<String,Object>();
        typeParam.put("deptId",deptId);
        typeParam.put("type",Constants.DOCTOR_TYPE_ODE);
        Map<String,String> typeMap = bsStaticParamService.getStaticParamsForMap(typeParam);

        //拼医生职称中文名字
        Doctor doctor =null;
        if(!CollectionUtils.isEmpty(doctors)){
        	for(int i = 0;i<doctors.size();i++){
        		doctor = doctors.get(i);
        		doctors.get(i).setDoctorTitleName(titleMap.get(doctor.getDoctorTitle()));
        		doctors.get(i).setPermissionName(typeMap.get(doctor.getPermission()));
            }
        }

        int total = doctorManagerService.getDoctorCountByDeptId(paramMap);
        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("draw", draw);
        retMap.put("recordsTotal", total);
        retMap.put("recordsFiltered", total);
        retMap.put("rows",doctors);

		logger.info("out getDoctorlist----arg==" + doctors);
		return retMap;
	}

	@ResponseBody
	@RequestMapping("/basicinfo/modify")
	public ResultModel<Map<String,String>> modifyDoctorBasic(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in getDepartmentBasic----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);

		String requestParam = jsonEsb.getString(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		 // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("rootGroupId");// 科室id
		Doctor doctor = JSON.parseObject(requestParam, Doctor.class);
        if(doctor == null){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，没有传医生信息");
        }

        doctor.setUpdateAuthor(authorId);
        doctor.setCreateAuthor(authorId);
        doctor.setDeptId(deptId);

        String doctorId = doctorManagerService.doctorModify(doctor);
		Map<String,String> rspBody = new HashMap<String,String>();
		rspBody.put("doctorId",doctorId);
		logger.info("out getDepartmentBasic----arg==" + doctorId);
		return new ResultModel<Map<String,String>>(rspBody);
	}

	/**
	 * 医生状态置失效 ---
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/basicinfo/remove")
	public ResultModel<Doctor> deleteDoctors(@RequestBody String jsonStr) throws Exception{
		logger.info("in deleteDoctors----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String ids= requestParam.getString("doctorIds");

        List<String> list = JSON.parseArray(ids, String.class);
        if(CollectionUtils.isEmpty(list)){
        	logger.debug("out deleteContact----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，要删除的医生ID不能为空");
        }
        doctorManagerService.deleteDoctorByIds(list);
		logger.info("out deleteDoctors----arg==");
		return new ResultModel<Doctor>(null);
	}

	/**
	 *
	 * @desc 医生门诊值班添加
	 * @param servletRequest
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/schedule/modify")
	public ResultModel<Map<String,String>> modifyDoctorSchedule(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in doctorScheduleModify----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);

		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
		String schedule = requestParam.getString("schedule");
		if(null == schedule){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无schedule节点！");
		}

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("rootGroupId");// 科室id

		ScheduleDuty scheduleDuty = JSON.parseObject(schedule, ScheduleDuty.class);
		scheduleDuty.setDeptId(deptId);
        String scheduleId = doctorManagerService.doctorScheduleModify(scheduleDuty,authorId);
		Map<String,String> rspBody = new HashMap<String,String>();
		rspBody.put("scheduleId",scheduleId);
		logger.info("out doctorScheduleModify----arg==" + scheduleId);
		return new ResultModel<Map<String,String>>(rspBody);
	}

	/**
	 *
	 * @desc 医生门诊值班添加
	 * @param servletRequest
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/schedule/remove")
	public ResultModel<Map<String,String>> removeSchedule(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in removeSchedule----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);

		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
		String flag = requestParam.getString("flag");
		String scheduleId = requestParam.getString("scheduleId");

		if(!StringUtils.isEmpty(flag) && "0".equals(flag)&& StringUtils.isEmpty(scheduleId)){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_SCHEDULEID_NOT_EXIST, "FLAG传0时,必须传scheduleId不能为空");
		}


		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("rootGroupId");// 科室id
        List<String> list = new ArrayList<String>();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("deptId",deptId);
//        map.put("flag",flag);
//        map.put("list",list);
        if(CollectionUtils.isEmpty(list)){
//        	doctorManagerService.getScheduleSByCondition(paramMap);
        	doctorManagerService.deleteAllSchedule(map);
        }else{
        	doctorManagerService.deleteScheduleByIds(list);
        }

		Map<String,String> rspBody = new HashMap<String,String>();
		logger.info("out removeSchedule----arg==" + scheduleId);
		return new ResultModel<Map<String,String>>(rspBody);
	}


	/**
	 * 根据科室Id 查询门诊排班详细信息
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/schedule/detail")
	public ResultModel<List<ScheduleDuty>> getScheduleSByCondition(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in getScheduleSByCondition----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("rootGroupId");// 科室id
        Map<String,Object> paramMap = requestParam;
        paramMap.put("deptId", deptId);
        List<ScheduleDuty> scheduleDutys = doctorManagerService.getScheduleSByCondition(paramMap);
		logger.info("out getScheduleSByCondition----arg==" + scheduleDutys);
		return new ResultModel<List<ScheduleDuty>>(scheduleDutys);
	}

	@ResponseBody
	@RequestMapping("/basicinfo/uploadHeadPic")
	public ResultModel<Object> uploadHeadPic(HttpServletResponse response, HttpServletRequest request) throws Exception{
			String filepath = "";
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
	            if (multipartResolver.isMultipart(request)) {
	                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
	                Iterator<String> iter = multiRequest.getFileNames();
	                if(iter.hasNext()){
		                while (iter.hasNext()) {
		                    MultipartFile file = multiRequest.getFile(iter.next());
		                    if(!file.isEmpty()){
		                    	filepath = OSSClientUtil.uploadPicture(file,PropertiesUtils.getProperty("doctorHead"));//保存图片
		                    }
		                }
	                }else{
		                throw new AppException(ErrorCode.FOLLOW_EXCEPTION_TYPE_UPLOAD_FILE_MPTY,"图片上传失败，上传文件为空");
		        }
	        }
            return new ResultModel<Object>(filepath);
		}

	@ResponseBody
	@RequestMapping("/basicinfo/uploadCertificate")
	public ResultModel<Object> uploadQrcode(HttpServletResponse response, HttpServletRequest request) throws Exception{
			String filepath = "";
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
	            if (multipartResolver.isMultipart(request)) {
	                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
	                Iterator<String> iter = multiRequest.getFileNames();
		            if(iter.hasNext()){
		                while (iter.hasNext()) {
		                    MultipartFile file = multiRequest.getFile(iter.next());
		                    if(!file.isEmpty()){
		                    	filepath = OSSClientUtil.uploadPicture(file,PropertiesUtils.getProperty("certificate"));//保存图片
		                    }
		                }
		            }else{
	                	throw new AppException(ErrorCode.FOLLOW_EXCEPTION_TYPE_UPLOAD_FILE_MPTY,"图片上传失败，上传文件为空");
	                }
	            }
            return new ResultModel<Object>(filepath);
		}
}
